/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package xdxn.editor.studio.utils;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import javax.imageio.ImageIO;

/**
 *
 * @author Cai Han
 */
public class FileUtils {

    private static final String ROOT_DIR = System.getProperty("user.dir");

    public FileUtils() {
    }

    public static void writeFile( String fileName , String content ) {
        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
        try {
            fos = new FileOutputStream(ROOT_DIR + fileName);
            osw = new OutputStreamWriter(fos);
            osw.write(content , 0 , content.length());
            osw.flush();
        } catch ( IOException e ) {
        } finally {
            try {
                if ( null != osw ) {
                    osw.close();
                }
                if ( null != fos ) {
                    fos.close();
                }
            } catch ( IOException e ) {
            }
        }
    }

    public static String readFile( String fileName ) {
        File file = new File(ROOT_DIR + fileName);
        if ( !file.exists() ) {
            return null;
        }
        InputStream is = null;
        String content = null;
        byte[] buffer = new byte[1024];
        int length;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            is = new FileInputStream(file);
            while ( (length = is.read(buffer)) != -1 ) {
                baos.write(buffer , 0 , length);
            }
            content = new String(baos.toByteArray() , "UTF-8");
        } catch ( FileNotFoundException ex ) {
        } catch ( IOException ex ) {
        } finally {
            if ( null != is ) {
                try {
                    is.close();
                } catch ( IOException ex ) {
                }
            }
        }
        return content;
    }

    public static BufferedImage readImage( String imageName ) {
        BufferedImage image = null;
        try {
            InputStream is = new BufferedInputStream(new FileInputStream(ROOT_DIR + imageName));
            image = ImageIO.read(is);
        } catch ( Exception e ) {
        }
        return image;
    }

    public static void writeImage( BufferedImage image , String imageName ) {
        File file = new File(ROOT_DIR + imageName);
        try {
            ImageIO.write(image , "PNG" , file);
        } catch ( IOException ex ) {
        }
    }
}
